package com.macro.mall.portal.controller;

import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.UmsMember;
import com.macro.mall.portal.service.UmsMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * 会员管理Controller
 * Created by macro on 2018/8/3.
 */
@Controller
@Api(tags = "UmsMemberController")
@Tag(name = "UmsMemberController", description = "会员登录注册管理")
@RequestMapping("/sso")
public class UmsMemberController {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private UmsMemberService memberService;

    private static final String APP_ID = "1072792244795667";
    private static final String APP_SECRET = "87d21f64a3a1d6456b4790846ee33a4a";

    /**
     * 登录 Facebook
     */
    @GetMapping("/loginWithFacebook")
    @ResponseBody
    public CommonResult loginWithFacebook(@RequestParam String accessToken) {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890)); // 按你的代理端口改
        factory.setProxy(proxy);
        factory.setConnectTimeout(5000);
        factory.setReadTimeout(5000);
        // 1️⃣ 验证 access_token 是否有效 1194980252696991
        String appAccessToken = APP_ID + "|" + APP_SECRET;
        String debugUrl = "https://graph.facebook.com/debug_token" +
                "?input_token=" + accessToken +
                "&access_token=" + appAccessToken;
        RestTemplate restTemplate = new RestTemplate(factory);
        Map debugResponse = restTemplate.getForObject(debugUrl, Map.class);
        Map<String, Object> data = (Map<String, Object>) debugResponse.get("data");
        if (data == null || !(Boolean) data.get("is_valid")) {
            return CommonResult.failed("access_token 无效");
        }
        // 3️⃣ 绑定或注册本地用户
        String facebookId = (String) data.get("user_id");
        //根据脸书id查询用户 若无则让用户绑定

        UmsMember user = memberService.selUserByFaceBookId(facebookId);
        if (user == null) {
            return CommonResult.failed("请先绑定手机号",facebookId,512);
        }
        String token = memberService.loginByFacebook(user.getUsername(), user.getPassword());
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }




    @ApiOperation("脸书绑定")
    @RequestMapping(value = "/faceBookBand", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult faceBookBand(@RequestParam String faceBookId,
                                 @RequestParam String telephone,
                                 @RequestParam String authCode) {
        memberService.faceBookBand(faceBookId, telephone, authCode);
        String token = memberService.loginByFacebook(telephone, telephone);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap,"绑定成功");
    }


    @ApiOperation("会员注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult register(@RequestParam String username,
                                 @RequestParam String password,
                                 @RequestParam String telephone,
                                 @RequestParam String authCode) {
        memberService.register(username, password, telephone, authCode);
        return CommonResult.success(null,"注册成功");
    }

    @ApiOperation("会员登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult login(@RequestParam String username,
                              @RequestParam String password) {
        String token = memberService.login(username, password);
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }


    @ApiOperation("会员验证码登录")
    @RequestMapping(value = "/codeLogin", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult codeLogin(@RequestParam String username,
                              @RequestParam String authCode) {
        String token = memberService.codeLogin(username, authCode);
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation("获取会员信息")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult info(Principal principal) {
        if(principal==null){
            return CommonResult.unauthorized(null);
        }
        UmsMember member = memberService.getCurrentMember();
        return CommonResult.success(member);
    }

    @ApiOperation("修改用户信息")
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateUser(@RequestBody UmsMember member) {
        String authCode = memberService.updateUser(member);
        return CommonResult.success(authCode);
    }

    @ApiOperation("获取验证码")
    @RequestMapping(value = "/getAuthCode", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getAuthCode(@RequestParam String telephone) {
        if (telephone.startsWith("86")){
            //将前两位截取掉
            telephone = telephone.substring(2);
            return CommonResult.success(memberService.generateAuthCodeChina(telephone),"获取验证码成功");
        }
        String authCode = memberService.generateAuthCode(telephone);
        return CommonResult.success(authCode,"获取验证码成功");
    }

    @ApiOperation("会员修改密码")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updatePassword(@RequestParam String telephone,
                                 @RequestParam String password,
                                 @RequestParam String authCode) {
        memberService.updatePassword(telephone,password,authCode);
        return CommonResult.success(null,"密码修改成功");
    }


    @ApiOperation(value = "刷新token")
    @RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = memberService.refreshToken(token);
        if (refreshToken == null) {
            return CommonResult.failed("token已经过期！");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }


    @ApiOperation("注销账号")
    @RequestMapping(value = "/cancel", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult cancel() {
        UmsMember member = memberService.getCurrentMember();
        member.setStatus(0);
        memberService.updateStatus(member);
        return CommonResult.success(member);
    }


    @ApiOperation("退出登录")
    @RequestMapping(value = "/loginOut", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult loginOut() {
        UmsMember member = memberService.getCurrentMember();
        return CommonResult.success(member);
    }
}
